package work.chenxr.security.event;

import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.stereotype.Component;
import work.chenxr.security.user.UserDetail;

/**
 * @Author Chenxr
 * @Date 2023/10/23
 * @Description 认证事件处理
 */
@Component
@AllArgsConstructor
public class AuthenticationEvents {

    @EventListener
    public void onSuccess(AuthenticationSuccessEvent event) {
        // 用户信息
        UserDetail user = (UserDetail) event.getAuthentication().getPrincipal();

        // 业务逻辑...
        // 比如保存日志
        System.out.println("登录成功!");
    }

    @EventListener
    public void onFailure(AbstractAuthenticationFailureEvent event) {
        // 用户名
        String username = (String) event.getAuthentication().getPrincipal();

        // 业务逻辑...
        // 比如保存日志
        System.out.println("登录失败!");
    }

}
